package cn.gok.oa.system.controller;


import cn.gok.oa.log.LogAnnotation;
import cn.gok.oa.system.dto.UserDto;
import cn.gok.oa.system.dto.UserListDto;
import cn.gok.oa.system.entity.TbUserDetail;
import cn.gok.oa.system.vo.UserListVo;
import cn.gok.oa.system.vo.UserVo;
import cn.gok.oa.system.entity.TbUser;
import cn.gok.oa.system.service.ITbMenuRoleService;
import cn.gok.oa.system.service.ITbUserDetailService;
import cn.gok.oa.system.service.ITbUserService;
import cn.gok.oa.util.DateUtil;
import cn.gok.oa.util.MD5Util;
import cn.gok.oa.util.ResultData;
import cn.gok.oa.util.UrlUtil;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.nio.file.Path;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gok
 * @since 2022-08-04
 */
@RestController
@RequestMapping("/user")
public class TbUserController {
    @Autowired
    ITbUserService iTbUserService;

    @Autowired
    ITbUserDetailService iTbUserDetailService;

    @Autowired
    ITbMenuRoleService iTbMenuRoleService;

    @RequestMapping(value = "/staff" ,method = RequestMethod.GET)
    @LogAnnotation("获取员工列表")
    public ResultData staff(UserListDto userListDto){
        Page<UserListVo> page = new Page<>(userListDto.getPage(),userListDto.getLimit());
        IPage<UserListVo> iPage = iTbUserService.getList(page,userListDto.getUserName(),userListDto.getPhone());
        return ResultData.page(iPage.getRecords(),iPage.getTotal());
    }


    @RequestMapping(value = "/login" ,method = RequestMethod.POST)
    @LogAnnotation("登录成功！")
    public ResultData login(String loginName, String password, HttpServletRequest httpServletRequest) {
        password = MD5Util.getMD5(password);
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(TbUser::getLoginName,loginName);
        queryWrapper.lambda().eq(TbUser::getPassword,password);
        TbUser one = iTbUserService.getOne(queryWrapper);
        if (one != null) {
            UserVo userVo = iTbUserService.getMessage(one);
            httpServletRequest.getSession().setAttribute("LOGIN_USER",one);
            ResultData result = new ResultData();
            result.setCode("0");
            result.setMsg("登录成功！");
            result.setData(userVo);
            //返回前端带TOKEN的数据
            return result;
        } else {
            ResultData result = new ResultData();
            result.setMsg("账号名或密码错误！");
            result.setCode("1");
            return result;
        }
    }

    @RequestMapping(value = "/addUser" ,method = RequestMethod.POST)
    @LogAnnotation("新增用户")
    @ResponseBody
    public ResultData addUser(@RequestBody UserDto userDto, HttpServletRequest httpServletRequest) {

        try {
            String token = httpServletRequest.getHeader("token");
            int modifyId = Integer.parseInt(JWT.decode(token).getAudience().get(0));
            userDto.setCreateId(modifyId);
            Integer id = iTbUserService.addUser(userDto);
            String path = UrlUtil.getUserDirectoryPath();
            // 文件下载的全路径
            String userPath = path + File.separator + id ;
            File file1 = new File(userPath);
            if (file1.mkdirs()) {
                return ResultData.success();
            }
            ResultData result = ResultData.fail();
            result.setMsg("用户初始化失败！");
            return result;


        } catch (RuntimeException e) {

            return ResultData.fail();
        }
        // 文件所在路径


    }


    @RequestMapping(value = "/updateUser" ,method = RequestMethod.PUT)
    @LogAnnotation("更新用户")
    @ResponseBody
    public ResultData updateUser(@RequestBody UserListVo userListVo,HttpServletRequest httpServletRequest) {
        try {
            String token = httpServletRequest.getHeader("token");
            int modifyId = Integer.parseInt(JWT.decode(token).getAudience().get(0));
            userListVo.setModifyId(modifyId);
            iTbUserService.updateUser(userListVo);
        } catch (RuntimeException e) {
            return ResultData.fail();
        }
        return ResultData.success();
    }

    @RequestMapping(value = "/deleteUser" ,method = RequestMethod.DELETE)
    @LogAnnotation("删除用户")
    public ResultData deleteUser(int userId,HttpServletRequest httpServletRequest){
        try {
            String token = httpServletRequest.getHeader("token");
            int modifyId = Integer.parseInt(JWT.decode(token).getAudience().get(0));
            iTbUserService.deleteUser(userId,modifyId);
        } catch (RuntimeException e) {
            return ResultData.fail();
        }
        return ResultData.success();
    }

    @RequestMapping(value = "/resetPwd" ,method = RequestMethod.PUT)
    @LogAnnotation("修改用户密码")
    public ResultData resetPwd(int userId,String password,HttpServletRequest httpServletRequest){
         password = MD5Util.getMD5(password);
         String token = httpServletRequest.getHeader("token");
         int modifyId = Integer.parseInt(JWT.decode(token).getAudience().get(0));
         int temp = iTbUserService.resetPwd(userId,password,modifyId);
         if (temp > 0 ){
             return ResultData.success();
         }
         return  ResultData.fail();
    }
}
